<?php

namespace LhpAmis\Renderers;


class BaseRenderer implements \JsonSerializable
{
    // use Macroable {
    //     __call as macroCall;
    // }

    public $type;
    public $isEditer = false;

    public $amisSchema = [];

    public static function make()
    {
        return new static();
    }
    /**
     * @param $type
     *
     * @return \LhpAmis\Renderers\Amis | \LhpAmis\Renderers\Component
     */
    public static function amis($type = null)
    {
        if (filled($type)) {
            return \LhpAmis\Renderers\Component::make()->setType($type);
        }
        return \LhpAmis\Renderers\Amis::make();
    }
    public function __call($method, $parameters)
    {
        return $this->set($method, array_shift($parameters));
    }
    public function unset($name)
    {
        unset($this->amisSchema[$name]);
        return $this;
    }
    public function set($name, $value)
    {
        if ($name == 'map' && is_array($value) && array_keys($value) == array_keys(array_keys($value))) {
            $value = (object) $value;
        }

        $this->amisSchema[$name] = $value;

        return $this;
    }
    /**
     * 批量设置
     * @param array $data
     * @return static
     */
    public function batchSet(array $data)
    {
        foreach ($data as $name => $value) {
            $this->set($name, $value);
        }
        return $this;
    }
    public function get($name)
    {
        return $this->amisSchema[$name];
    }
    public function jsonSerialize(): array
    {
        return $this->filteredResults();
    }

    public function toJson()
    {
        return json_encode($this->amisSchema);
    }

    public function toArray()
    {
        return $this->amisSchema;//json_decode(json_encode($this->amisSchema), true);
    }

    /**
     * @param string $sign         权限标识
     * @param mixed  $replaceValue 无权限时替换的值
     *
     * @return $this
     */
    public function permission(string $sign, $replaceValue = '')
    {
        $this->amisSchema['owl_permission'] = $sign;
        $this->amisSchema['owl_permission_replace_value'] = $replaceValue;

        return $this;
    }

    public function filteredResults(): array
    {
        return $this->amisSchema;
    }


    protected function getBuilderMaps()
    {
        $builderMapFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'builderMap.php';
        if (file_exists($builderMapFile)) {
            return require $builderMapFile;
        }
        return [];
    }
    /**
     * 
     * @param mixed $args
     * @return TableColumn
     */
    public function crudBuildField($args)
    {
        $Field = Amis::make()->TableColumn($args['name'], $args['label'])->remark($args['remark'])->type($args['type']);
        $Field->formBuildField($args);
        return $Field;
    }
    /**
     * 获取数组中指定位置的元素（从1开始计数），按数组实际排序顺序
     * 
     * @param array $array 要操作的数组
     * @param int $position 位置，从1开始
     * @return mixed 指定位置的元素，或false（如果位置不存在）
     */
    protected function get_array_element_by_position(array $array, int $position)
    {
        // 检查位置是否有效（大于0）
        if ($position < 1) {
            return false;
        }

        // 重置数组指针到开头
        reset($array);

        // 移动指针到指定位置
        for ($i = 1; $i < $position; $i++) {
            if (next($array) === false) {
                return false; // 位置超出数组范围
            }
        }

        // 返回当前元素或false
        return current($array) ?: false;
    }
    public function extendsAttributes(array $item, int $arrayItemNumber = 0)
    {
        if ($arrayItemNumber > 0) {
            $extendsAttributes = $this->get_array_element_by_position($item, $arrayItemNumber);
            if ($extendsAttributes && is_array($extendsAttributes) && !empty($extendsAttributes)) {
                foreach ($extendsAttributes as $key => $value) {
                    $this->set($key, $value);
                }
            }
        }
    }
    /**
     * 组件参数构建
     * @param string $baseParams
     * @param string|object $name
     * @param string $label
     * @param string $type
     * @param string $remark
     * @param mixed ...$options 额外选项，最后一个数组参数会被拆解，其他数组参数会被合并
     * @return $this
     */
    public function buildParams(array $baseParams, $name, string $label = '', string $type = 'text', ...$options): array
    {
        $remark = '';
        $normalOptions = [];
        $lastArrayOption = [];

        // 处理选项参数
        foreach ($options as $key => $option) {
            if ($key === 0 && is_string($option)) {
                // 第一个选项参数视为remark
                $remark = $option;
            } elseif (is_array($option)) {
                // 如果是数组且是最后一个参数，标记为最后数组选项
                if ($key === count($options) - 1) {
                    $lastArrayOption = $option;
                } else {
                    $normalOptions[] = $option;
                }
            } else {
                $normalOptions['option' . $key] = $option;
            }
        }
        // 合并普通选项
        $mergedOptions = [];
        foreach ($normalOptions as $option) {
            if (is_array($option)) {
                $mergedOptions = array_merge($mergedOptions, $option);
            } else {
                $mergedOptions[] = $option;
            }
        }

        // 合并最后一个数组选项（拆解）
        $finalOptions = array_merge($mergedOptions, $lastArrayOption);
        $baseParams = array_merge($baseParams, $finalOptions);

        return $baseParams;
    }
    /**
     * 设置是否需要编辑
     * @param bool $isEditer
     * @return void
     */
    protected function setTableIsEditer(bool $isEditer = false)
    {
        $this->isEditer = $isEditer;
        return $this;
    }


    protected function checkTableEdit()
    {

        if (!$this->isEditer && strpos($this->get('type'), 'input-') !== false) {
            $this->set('type', str_replace('input-', '', $this->get('type')));
        }
    }
}
